﻿using System.Data;
using MediatR;
using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using Return.Enum;
using SlaughterItem.Common.Infrastructures.Interfaces;
using THE_WIND_RISES.Common.Domans.Produce.DemandPlanning;
using THE_WIND_RISES.Common.Dtos;

namespace Production_Set.API.MaterialManagement.Export
{
    public class MaterialPlanningExportHandler : IRequestHandler<MaterialPlanningExportCommon, Result>
    {
        private readonly IBaseRepository<MaterialPlanning> MaterialPlanningRepository;
        public MaterialPlanningExportHandler(IBaseRepository<MaterialPlanning> materialPlanningRepository)
        {
            MaterialPlanningRepository=materialPlanningRepository;
        }
        public async Task<Result> Handle(MaterialPlanningExportCommon request, CancellationToken cancellationToken)
        {
            var results = new Result() { Code = (int)CommonErrorCodes.Delete };
            try
            {
                //创建一个表格
                DataTable dtNpoi = new DataTable();
                //工作表路径
                string fileName = Directory.GetCurrentDirectory() + @"\\wwwroot\\Excel\\" + request.ExportName + "";
                //定义工作表名称
                string sheetName = "物料需求计划表";
                //判断第一行是否是列名
                bool isColumnName = true;
                //工作簿接口
                IWorkbook workbook;
                //获取文件扩展名
                string fileExt = Path.GetExtension(fileName).ToLower();
                //添加数量
                int AddNum = 0;
                //创建文件流
                using (FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read))
                {
                    //XSSF是用于.xlsx（2007以后版本）
                    //HSSF是用于.xls（2007以前版本）
                    if (fileExt == ".xlsx")
                    {
                        workbook = new XSSFWorkbook(fs);
                    }
                    else
                    {
                        workbook = new HSSFWorkbook(fs);
                    }
                    //导入成功
                    //实例化sheet
                    ISheet sheet = null;
                    if (sheetName != null && sheetName != "")
                    {
                        sheet = workbook.GetSheet(sheetName);
                        if (sheet == null)
                        {
                            //获取表格
                            sheet = workbook.GetSheetAt(0);
                        }
                    }
                    else
                    {
                        sheet = workbook.GetSheetAt(0);
                    }
                    for (int i = sheet.FirstRowNum + 1; i <= sheet.LastRowNum; i++)
                    {
                        IRow row = sheet.GetRow(i);
                        var AddMainplanData = "insert into MaterialPlanning values(@MaterialPlanningId,@PlanningCode,@PlanningName,@PlanningDesc,@PlanningState,@PlanningPeole,@DepartmentId,@Handle,@HandleContext,@HandleTime,@Pid,@IsDelete)";
                        var AddNowNum = MaterialPlanningRepository.Add(AddMainplanData, new
                        {
                            MaterialPlanningId = 0,
                            PlanningCode = row.GetCell(1).ToString(),
                            PlanningName = row.GetCell(2).ToString(),
                            PlanningDesc = row.GetCell(3).ToString(),
                            PlanningState = row.GetCell(4).ToString() == "新建" ? 1 : (row.GetCell(4).ToString() == "确认" ? 2 : 3),
                            PlanningPeole = row.GetCell(5).ToString(),
                            DepartmentId = row.GetCell(6).ToString() == "JAVA组" ? 1 : (row.GetCell(6).ToString() == "JAVA2组" ? 2 : 3),
                            Handle = row.GetCell(7).ToString(),
                            HandleContext = row.GetCell(8).ToString(),
                            HandleTime = DateTime.Parse(row.GetCell(9).ToString()),
                            Pid = row.GetCell(10).ToString() == "创建" ? 1 : (row.GetCell(6).ToString() == "审批" ? 2 : 3),
                            IsDelete = (row.GetCell(11).ToString()=="禁用"? true:false)
                        });
                        if (AddNowNum > 0)
                        {
                            AddNum++;
                        }
                    }
                    if (AddNum > 0)
                    {
                        results.Code = (int)CommonErrorCodes.Success;
                        return results;
                    }
                    else
                    {
                        return results;
                    }
                }
            }
            catch (Exception ex)
            {

                throw ex;
            }
        }

    }
}
